import RPi.GPIO as GPIO
import time

# 设置GPIO模式为BCM
GPIO.setmode(GPIO.BCM)

# 定义超声波模块的引脚
TRIG_PIN = 12
ECHO_PIN = 16

# 定义蜂鸣器的引脚
BUZZER_PIN = 7

# 设置引脚为输出模式

GPIO.setup(TRIG_PIN, GPIO.OUT)
GPIO.setup(ECHO_PIN, GPIO.IN)
GPIO.setup(BUZZER_PIN, GPIO.OUT)
GPIO.output(BUZZER_PIN, GPIO.HIGH)
def measure_distance():
    # 发送一个10us的高电平脉冲来触发超声波发射
    GPIO.output(TRIG_PIN, True)
    time.sleep(0.00001)
    GPIO.output(TRIG_PIN, False)

    # 等待接收超声波回波
    while GPIO.input(ECHO_PIN) == 0:
        pulse_start = time.time()

    while GPIO.input(ECHO_PIN) == 1:
        pulse_end = time.time()

    # 计算回波的持续时间，并根据声速计算距离（假设声速为343m/s）
    pulse_duration = pulse_end - pulse_start
    distance = pulse_duration * 34300 / 2  # 将秒转换为厘米
    return distance

def buzz(duration):
    try:
        # 产生蜂鸣器声音
        GPIO.output(BUZZER_PIN, GPIO.LOW)
        time.sleep(duration)
        GPIO.output(BUZZER_PIN, GPIO.HIGH)
    except Exception as e:
        print("Error in buzz function:", e)

try:
    while True:
        distance = measure_distance()
        print(distance)
        
        if distance>50:
            buzz(0.5)
        
        buzz(distance/100.0)

        time.sleep(0.1)  # 间隔0.1秒

except KeyboardInterrupt:
    GPIO.cleanup()  # 清理GPIO状态

